package com.hao.demo1;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

// 练习Thread，实现多线程同步下载图片
public class TestThread2 extends Thread {
    private String url; // 地址
    private String name; // 保存的文件名
    public TestThread2(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public TestThread2() {
    }
    // 下载文件的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件"+name);
    }

    public static void main(String[] args) {
        TestThread2 testThread1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片1.jpg");
        TestThread2 testThread2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片2.jpg");
        TestThread2 testThread3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片3.jpg");
        testThread1.start();
        testThread2.start();
        testThread3.start();
    }
}



// 下载器
class WebDownloader{
    // 下载方法
    public void downloader(String url,String name)  {

        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader出问题了");
        }
    }
}
